/**
 * Created by 郭欣光 on 2018/2/14.
 */
var releaseExperimentCharacteristic = false;
var gotoExperimentalReportCharacteristic = false;
var gotoNodeManagementCharacteristic = false;
var userName = "";


function login() {
    var id = document.getElementById("id").value;
    var password = document.getElementById("password").value;
    var checkCode = document.getElementById("checkCode").value;
    if(id === "" || password === "" || checkCode === "") {
        // alert("所有字段不允许为空！");
        document.getElementById("loginError").style.display = "block";
        document.getElementById("loginErrorMessage").innerHTML = "所有字段不可以为空！";
        document.getElementById("checkCodeImage").src = "/apis/checkcode/get_check_code?imageId=" + Math.random();
        setTimeout(clearLoginError, 1500);
        return false;
    }
    const obj = {};
    obj.id = id;
    obj.password = password;
    obj.checkCode = checkCode;
    var token = getCookie("token");
    $.ajax({
        url: "/apis/user/login",
        type: "POST",
        cache: false,//设置不缓存
        dataType:"json",
        headers: {
            token: token //这里是Token
        },
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(obj),
        success: loginSuccess,
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            showErrorInfo(XMLHttpRequest,textStatus,errorThrown);
        }
    });
    return false;
}

function loginSuccess(data) {
    if(data.flag) {
        setTokenToCookie(data.token);
        getUserInfo();
        document.getElementById("closeLogin").click();
    } else {
        // alert(data);
        document.getElementById("loginError").style.display = "block";
        document.getElementById("loginErrorMessage").innerHTML = data.msg;
        document.getElementById("checkCodeImage").src = "/apis/checkcode/get_check_code?imageId=" + Math.random();
        setTimeout(clearLoginError, 1500);
        return false;
    }
}

function clearLoginError() {
    if(document.getElementById("loginError").style.display.indexOf("block") === 0) {
        document.getElementById("loginError").style.display = "none";
        document.getElementById("loginErrorMessage").innerHTML = "";
    }
}

function signOut() {
    deleteCookie("token");
    if ("no" === getCookie(token)){
        parent.location.reload();
    }else {
        alert("注销失败");
    }
}

function releaseExperiment() {
    gotoExperimentalReportCharacteristic = false;
    gotoNodeManagementCharacteristic = false;
    releaseExperimentCharacteristic = true;
    getUserInfo();
}

function getInitUserSuccess(data) {
    if(!data.flag) {
        // 当前未登录，将跳转至登录页面
        document.getElementById("checkCodeImage").src = "/apis/checkcode/get_check_code?imageId=" + Math.random();
        document.getElementById("userLogin").click();
    } else {
        var user = JSON.parse(data.msg);
        userName = user['name'];
        var role = user['role'];
        if (role.indexOf("教师") === 0) {
            teacherGetCoursesTop5();
        } else {
            var str = "<ul class='nav navbar-nav'>" +
                "<li class='dropdown'>" +
                "<a href='javascript:void(0);' class='dropdown-toggle' data-toggle='dropdown'>" +
                "我的课程" +
                "</a>" +
                "<ul class='dropdown-menu'>" +
                "<li><a class='' href='#'>Linux基础入门新版</a></li>" +
                "<li><a class=''  href='#'>高级bash编程指南</a></li>" +
                "<li><a class=''  href='#'>java实现记事本</a></li>" +
                "<li><a class='' href='#' >python实现文字聊天室</a></li>" +
                "<li><a class=''  href='#'>查看更多</a></li>" +
                "</ul>" +
                "</li>" +
                "</ul>" +
                "<ul class='nav navbar-nav'>" +
                "<li class='dropdown'>" +
                "<a href='javascript:void(0);' class='dropdown-toggle' data-toggle='dropdown'>" +
                "欢迎您，" + userName +
                "</a>" +
                "<ul class='dropdown-menu'>" +
                "<li><a class='' href='/home/index.html' >我的主页</a></li>" +
                "<li><a class='' href='#' onclick='javascript:signOut(); return false;' data-toggle='modal' data-target='#signOutModel'>退出登录</a></li>" +
                "</ul>" +
                "</li>" +
                "</ul>";
            document.getElementById("userInfo").innerHTML = str;
        }
        setTokenToCookie(data.token)
    }
    return false;
}


function teacherGetCoursesTop5() {
    var token = getCookie("token");
    $.ajax({
        url: "/apis/course/get_my_courses_top_number?topNumber=5",
        type: "GET",
        cache: false,//设置不缓存
        headers: {
            token: token //这里是Token
        },
        success: teacherGetCoursesTop5Success,
        error: showErrorInfo
    });
}

function teacherGetCoursesTop5Success(data) {
    var data = JSON.parse(data);
    var courseList = data['teacherCourses'];
    if(data.result=="error: 没有课程！") {
        //当前教师没有有课程
        var str = "<ul class='nav navbar-nav'>" +
            "<li class='dropdown'>" +
            "<a href='javascript:void(0);' class='dropdown-toggle' data-toggle='dropdown'>" +
            "我的课程" +
            "</a>" +
            "<ul class='dropdown-menu'>" +
            "<li><a class='' href=''>" + "没有课程" + "</a></li>" +
            "</ul>" +
            "</li>" +
            "</ul>" +
            "<ul class='nav navbar-nav'>" +
            "<li class='dropdown'>" +
            "<a href='javascript:void(0);' class='dropdown-toggle' data-toggle='dropdown'>" +
            "欢迎您，" + userName +
            "</a>" +
            "<ul class='dropdown-menu'>" +
            "<li><a class='' href='/home/index.html' >我的主页</a></li>" +
            "<li><a class='' href='/add_user/index.html' >添加用户</a></li>" +
            "<li><a class='' href='/back_stage/index.html' >后台管理</a></li>" +
            "<li><a class='' href='' onclick='signOut(); return false;' data-toggle='modal' data-target='#signOutModel'>退出登录</a></li>" +
            "</ul>" +
            "</li>" +
            "</ul>";
        document.getElementById("userInfo").innerHTML = str;
    } else {
        // 当前老师有课程
        var str = "<ul class='nav navbar-nav'>" +
            "<li class='dropdown'>" +
            "<a href='javascript:void(0);' class='dropdown-toggle' data-toggle='dropdown'>" +
            "我的课程" +
            "</a>" +
            "<ul class='dropdown-menu'>";
        //var courses = JSON.parse(data)['teacherCourses'];
        for(var i = 0; i < courseList.length; i++) {
            var course = courseList[i];
            str += "<li><a class='' href='/developer/course_information.html?courseID=" + course.id + "'>" + course.name + "</a></li>";
        }
        if (courseList.length >= 5) {
            str += "<li><a class=''  href='/developer/index.html'>查看更多</a></li>" ;
        }
        str += "</ul>" +
            "</li>" +
            "</ul>" +
            "<ul class='nav navbar-nav'>" +
            "<li class='dropdown'>" +
            "<a href='javascript:void(0);' class='dropdown-toggle' data-toggle='dropdown'>" +
            "欢迎您，" + userName +
            "</a>" +
            "<ul class='dropdown-menu'>" +
            "<li><a class='' href='/home/index.html' >我的主页</a></li>" +
            "<li><a class='' href='/add_user/index.html' >添加用户</a></li>" +
            "<li><a class='' href='/back_stage/index.html' >后台管理</a></li>" +
            "<li><a class='' href='' onclick='signOut(); return false;' data-toggle='modal' data-target='#signOutModel'>退出登录</a></li>" +
            "</ul>" +
            "</li>" +
            "</ul>";
        document.getElementById("userInfo").innerHTML = str;
    }
}

function gotoExperimentalReport() {
    releaseExperimentCharacteristic = false;
    gotoNodeManagementCharacteristic = false;
    gotoExperimentalReportCharacteristic = true;
    getUserInfo();
}

function gotoNodeManagement() {
    releaseExperimentCharacteristic = false;
    gotoExperimentalReportCharacteristic = false;
    gotoNodeManagementCharacteristic = true;
    getUserInfo();
}

$(document).ready(function () {
    var token = getCookie("token");
    if (token === "no") {
        document.getElementById("checkCodeImage").src = "/apis/checkcode/get_check_code?imageId=" + Math.random();
        document.getElementById("userLogin").click();
    }else {
        $.ajax({
            url: "/apis/user/loginByToken",
            type: "POST",
            dataType:"json",
            contentType: "application/json;charset=UTF-8",
            headers: {
                token: token //这里是Token
            },
            cache: false,//设置不缓存
            success: getInitUserSuccess,
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                showErrorInfo(XMLHttpRequest,textStatus,errorThrown);
            }
        });
        getCoursesTop4();
        getCoursesCountByTab();
    }
});
function getCookie(name) {
    var cookieValue = "no";
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = $.trim(cookies[i]);
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
function setTokenToCookie(value) {
    var Days = 1; //此 cookie 将被保存 30 天
    var exp = new Date();
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
    document.cookie = "token =" + escape(value) + ";expires=" + exp.toGMTString();
}
function deleteCookie(key) {
    var date = new Date();
    date.setTime(date.getTime() - 1);
    var delValue = getCookie(key);
    if (!!delValue) {
        document.cookie = key+'='+delValue+';expires='+date.toGMTString();
    }
}

function sleep(numberMillis) {
    var now = new Date();
    var exitTime = now.getTime() + numberMillis;
    while (true) {
        now = new Date();
        if (now.getTime() > exitTime)
            return;
    }
}
